package chapter4;

import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author caiya
 * @date 2020/3/25 22:27
 */
public class ReentrantReadWriteLockList {
    private ArrayList<String> arrayList = new ArrayList<>();
    private volatile ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();

    /**
     * 添加
     * @param e
     */
    public void add(String e) {
        writeLock.lock();
        try {
            arrayList.add(e);
        }finally {
            writeLock.unlock();
        }
    }

    /**
     * 删除
     * @param e
     */
    public void remove(String e) {
        writeLock.lock();
        try {
            arrayList.remove(e);
        }finally {
            writeLock.unlock();
        }
    }

    /**
     * 查询
     * @param index
     * @return
     */
    public String get(int index) {
        readLock.lock();
        try {
            return arrayList.get(index);
        }finally {
            readLock.unlock();
        }
    }
}
